from app.apSheduler import APScheduler
from .tasks import task_func
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime
# import croniter
from croniter import croniter
from .db import get_conn

# croniter库解析Linux cron格式的计划


class TaskView():

    def __init__(self, ) -> None:
        self.crontab = ""
        self.id = ""
        self.task_id = ""

    # 以添加为例子 暂停 删除 恢复可以根据业务场景自己写接口
    def add_crontab_task(self, params):
        """添加一个crontab任务"""
        try:
            self.crontab = params.get("crontab")
            self.id = params.get("id")
            self.task_id = params.get("task_id")
        except Exception as e:
            return False, str(e)
        # 记录数据库
        res = True
        engine, tbl = get_conn()
        with engine.connect() as conn:
            row = conn.execute(tbl.insert().values({
                    "crontab":self.crontab,
                    "id":self.id,
                    "task_id":self.task_id
                }))
            if row.rowcount > 0:
                res = True
            conn.commit()
        # print(CronTrigger.from_crontab(self.crontab))
        # 更新任务信息
        APScheduler().add_job(jobid=str(row.lastrowid), func=task_func,
                            args=(self.task_id,), trigger=CronTrigger.from_crontab(self.crontab))
        if res is False:
            return False, "数据库操作异常"
        return True, croniter(self.crontab, datetime.now()).get_next(datetime)

    def get_next_execute_time(self, params):
        """获取下一次执行时间"""
        try:
            self.crontab = params.get("crontab")
        except Exception as e:
            return False, str(e)
        return True, str(croniter(self.crontab, datetime.now()).get_next(datetime))
